package com.damai.action.aop.impl;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

import javax.servlet.http.HttpServletRequest;

import com.citywithincity.api.ApiConfig;
import com.damai.action.aop.Invoker;
import com.damai.error.ApiError;

class MethodInvoker implements Invoker {
	private Object controller;
	private Method method;
	
	public MethodInvoker(Object controller,Method method){
		this.controller = controller;
		this.method = method;
	}
	@Override
	public Object invoke(HttpServletRequest request, Object[] args) {
		final Object controller  = this.controller;
		final Method method = this.method;
		try {
			return method.invoke(controller, args);
		} catch (IllegalAccessException e) {
			throw new RuntimeException(e);
		} catch (IllegalArgumentException e) {
			throw new ApiError(new StringBuilder(50).append("非法参数:").append(e.getMessage()).toString(),e);
		} catch (InvocationTargetException e) {
			Throwable throwable = e.getTargetException();
			ApiConfig.error(throwable);
			if(throwable instanceof RuntimeException){
				throw (RuntimeException)throwable;
			}
			throw new RuntimeException(throwable);
		}
	}


}
